package com.jinliang.blogweb.config;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Order(0)
//@Component
public class CrosFilter implements Filter {
	
	private String[] whiteList= {"http://192.168.100.104:8848","http://127.0.0.1:8848","http://localhost:63342","http://127.0.0.1:8848","http://localhost:8080","http://192.168.100.104:8080"};
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) request; //
		HttpServletResponse hresp = (HttpServletResponse) response;
		String header = hreq.getHeader("Origin");
		for (String address : whiteList) {
			if(header==null){
				hresp.setHeader("Access-Control-Allow-Origin", "*"); // 设置相应头
				hresp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
				break;
			}
			if (header.equals(address)) {
				hresp.setHeader("Access-Control-Allow-Origin", address); // 设置相应头
				hresp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
				break;
			}
		}
		// 跨域
		//hresp.setHeader("Access-Control-Allow-Origin", "http://localhost:8080"); // 设置相应头
		// 跨域 Header
		hresp.setHeader("Access-Control-Allow-Methods", "*");
		hresp.setHeader("Access-Control-Allow-Credentials", "true");
		hresp.setHeader("Access-Control-Allow-Headers",
				"Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,x-requested-with,requesttype");
		hresp.setHeader("Access-Control-Max-Age", "600");
		// 配置options的请求返回
		if (hreq.getMethod().equals("OPTIONS")) { // 如果发现该请求为OPTION,则直接返回（不需要进入系统），并且设置相应信息
			hresp.setStatus(200);
			// hresp.setContentLength(0);
			hresp.getWriter().write("OPTIONS returns OK");
			return;
		}
		// Filter 只是链式处理，请求依然转发到目的地址。
		chain.doFilter(request, response);

	}

}
